<template>
  <div v-if="useModalForm" ref="dialogRef">
    <el-dialog
      v-model="dialogVisible"
      v-bind="$attrs"
      :destroy-on-close="true"
      :width="width"
      draggable
      :close-on-click-modal="false"
    >
      <ProForm
        ref="proFormBox"
        v-model:visible="dialogVisible"
        :options="options"
        :form-cols="formCols"
        :form-attrs="formAttrs"
        @get-model="(form: any) => $emit('getModel', form)"
        @cancel="(flag: boolean) => $emit('cancel', flag)"
        @validate-form="(form: any) => $emit('submitForm', form)"
      >
        <template #formBottom>
          <slot name="formBottom" />
        </template>
      </ProForm>
    </el-dialog>
  </div>
</template>
<script setup lang="ts">
import { optionsProps, FormProps } from '@/components/ProForm/interface';
import { FormWIdthEnum } from '@/enums';
import { ref, watch, useAttrs } from 'vue';

export interface ProFormProps {
  options: optionsProps[];
  visible: boolean;
  minWidth?: number;
  formAttrs?: FormProps;
  formCols?: number;
}
const props = withDefaults(defineProps<ProFormProps>(), {
  options: () => [],
  formCols: 3,
  visible: false,
  minWidth: FormWIdthEnum.minWidth
});

const $emit = defineEmits(['update:visible', 'getModel', 'cancel', 'submitForm']);

const proFormBox = ref();
const dialogRef = ref();

let dialogVisible = ref(props.visible);
const attrs = useAttrs() as { width: string };
let width = ref();
let useModalForm = ref(false);
// 断点变化时执行 findIndex
watch(
  () => props.visible,
  val => {
    dialogVisible.value = val;
    if (!useModalForm.value && val) {
      useModalForm.value = val;
    }
    if (val) {
      setWidth();
    }
  }
);
// 断点变化时执行 findIndex
watch(
  () => dialogVisible.value,
  val => {
    $emit('update:visible', val);
  }
);

onMounted(() => {
  window.addEventListener('resize', setWidth);
});

onUnmounted(() => {
  window.removeEventListener('resize', setWidth);
});

// 设置弹框大小
const setWidth = () => {
  nextTick(() => {
    const offsetWidth = dialogRef.value?.offsetWidth;
    if (!offsetWidth) return;

    if (offsetWidth < FormWIdthEnum.formMinWidth) {
      width.value = props.minWidth + 'px';
    } else {
      width.value = attrs?.width || FormWIdthEnum.col1;
    }
  });
};
defineExpose({
  proFormBox
});
</script>
